#
#	Handles HTML display, forms, etc.
#
#	2009, Mike Widner <mikewidner@gmail.com>
#
################

package Fangcheng::CGI::Display;

use 5.006001;
use strict;
use warnings;
use vars qw( $AUTOLOAD @ISA );

use Carp;
use Fangcheng::CGI;
use Fangcheng::Calc::Determinants;

@ISA = qw( Fangcheng::CGI );

my $VERSION = '0.01';

# just call our parent's constructor
# no constructor will lead compiler to generate one for us, which is not what we want here
sub new {
	my ($class, @args) = @_;
	return( bless $class->SUPER::new( @args ), ref($class) || $class );
}

# outputs matrix in form of HTML table
sub matrixTable {
	my ($self, $matrix) = @_;
	my $calc = Fangcheng::Calc::Determinants->new();
	my $string = '<table>';
	foreach my $row ( 1 .. $matrix->rows ) {
		$string .= '<tr>';
		foreach my $col ( 1 .. $matrix->columns ) {
			$string .= '<td>';
			my $val = $matrix->get( $row, $col );
			if ( $calc->canSetField( $matrix, $row, $col ) == 1 ) {
				$string .= $self->query->textfield(	-name 		=> "USERINPUT[$row][$col]",
													-default	=> $matrix->get( $row, $col ),
													-size		=> "5",
													-maxlength	=> "5",
													-border		=> "0" );
			}
			else {
				$string .= $matrix->get( $row, $col );			
			}
			$string .= '</td>';
		}
		$string .= '</tr>';
	}
	$string .= '</table>';
	return( $string );
}

# take a user-defined matrix and put it into a matrix object
sub userMatrix {
	my ($self, $matrix) = @_;
	foreach my $param ( $self->query->param ) {
		next if ( $param !~ /^USERINPUT\[(\d+)\]\[(\d+)\]/ );
		my ($row, $col) = ($1, $2);
		$matrix->set( $row, $col, $self->query->param( $param ) );
	}
	return( $matrix );	
}

# display an error message
sub error {
	my ($self, $error) = @_;
	
	# Will modify to save state, reload page for correction
	# but works for testing purposes now
	print "$error";
	$self->query->end_html;
	exit(0);
}

1;